package vn.edu.saigontech.ncms.service.impl;

import java.util.Collection;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import vn.edu.saigontech.ncms.model.user.User;
import vn.edu.saigontech.ncms.service.ReceiptService;
import vn.edu.saigontech.ncms.service.UserService;
@SuppressWarnings("unchecked")
public class UserServiceImpl extends HibernateGenericService<User, Long> implements UserService {

	public User findByUsername(String username) {
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.eq("username", username));
		return (User) criteria.uniqueResult();
	}
	
	@Override
	public Collection<User> findAll() {
		Criteria criteria = this.createCriteria();
		criteria.addOrder(Order.asc("firstName"));
		return criteria.list();
	}
	
	public Collection<User> findAllAreActive() {
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.eq("active", true));
		criteria.addOrder(Order.asc("firstName"));
		return criteria.list();
	}

	@Override
	public Collection<User> findByRole(String roleName) {
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.eq("active", true));
		criteria.createCriteria("roles").add(Restrictions.eq("name", roleName));
		criteria.addOrder(Order.asc("firstName"));
		return criteria.list();
	}
	
	@Override
	public Collection<User> findAllByRole(String roleName) {
		Criteria criteria = this.createCriteria();
		criteria.createCriteria("roles").add(Restrictions.eq("name", roleName));
		criteria.addOrder(Order.asc("firstName"));
		return criteria.list();
	}

	@Override
	public User login(String username, String password) {
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.eq("username", username));
		criteria.add(Restrictions.eq("password", password));
		return (User) criteria.uniqueResult();
	}
	
	@Override
	public boolean deleteById(Long id) {
		if(ReceiptService.INSTANCE.countByUserId(id) > 0) {
			return false;
		}
		return super.deleteById(id);
	}

	@Override
	public Collection<User> findAllNotAdmin() {
		Criteria criteria = this.createCriteria();
		criteria.add(Restrictions.eq("active", true));
		criteria.add(Restrictions.ne("username", "admin"));
		criteria.addOrder(Order.asc("firstName"));
		return criteria.list();
	}
}